package com.example.expandablelistview.fragmentdialog;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;

import com.example.expandablelistview.R;

public class CheckDialogFragment extends DialogFragment {
	NoticeDialogListener mListener;
	ArrayList<Integer> mSelect = new ArrayList<Integer>();

	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (NoticeDialogListener) activity;
		} catch (ClassCastException e) {
			String msg = " must implement NoticeDialogListener";
			throw new ClassCastException(activity.toString() + msg);
		}
	}

	public interface NoticeDialogListener {
		public void onDialogClick(DialogFragment dialog, String res);
	}

	public Dialog onCreateDialog(Bundle savedInstanceState) {
		return new AlertDialog.Builder(getActivity())
				.setIcon(R.drawable.ic_launcher)
				.setTitle("과일을 선택하시오")
				.setMultiChoiceItems(R.array.fruits, null,
						new OnMultiChoiceClickListener() {
							public void onClick(DialogInterface dialog,
									int which, boolean isChecked) {
								if (isChecked) {
									mSelect.add(which);
								} else if (mSelect.contains(which)) {
									mSelect.remove(which);
								}
							}
						}).setPositiveButton("확인", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String[] fruits = getResources().getStringArray(
								R.array.fruits);
						StringBuilder sb = new StringBuilder();
						for (int idx : mSelect) {
							sb.append(fruits[idx] + ", ");
						}
						sb.delete(sb.length() - 2, sb.length() - 1);
						mListener.onDialogClick(CheckDialogFragment.this,
								sb.toString());
					}
				}).setNegativeButton("취소", null).create();
	}
}
